package cz.cuni.amis.episodic.bayes.memories.eval;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class TimeStats {

	static final FileFilter dirFilter = new FileFilter() {

		@Override
		public boolean accept(File pathname) {
			return pathname.isDirectory();
		}
	};

	static double[] getStats(File statsFile) throws IOException {
		FileReader fileReader = new FileReader(statsFile);
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		String line;
		double mean = 0;
		boolean timeSection = false;
		while ((line = bufferedReader.readLine()) != null) {
			if (timeSection) {
				if (line.startsWith("mean:")) {
					mean = Double.parseDouble(line.split(" ")[1]);
				} else if (line.startsWith("std dev:")) {
					double stdDev = Double.parseDouble(line.split(" ")[2]);
					fileReader.close();
					return new double[] { mean, stdDev };
				}
			} else if (line.contains("TIME"))
				timeSection = true;
		}
		fileReader.close();
		return null;
	}

	public static void reportTimeStats(File expRootDir) throws IOException {
		// list all dirs ... these are models

		PrintStream out = System.out;

		out.println("Results are in micro seconds.");

		for (File modelDir : expRootDir.listFiles(dirFilter)) {
			out.println(modelDir.getName());
			List<String> row = new ArrayList<>();
			for (File strategyModelDir : new File(modelDir, "stats")
					.listFiles(dirFilter)) {

				out.println(strategyModelDir.getName());
				double[] stats = getStats(new File(strategyModelDir,
						"stats.txt"));
				long order = 1000;
				long m = Math.round(stats[0] / order);
				long sd = Math.round(stats[1] / order);
				row.add("$" + m + "\\pm" + sd+"$");
			}
			out.print(StringUtils.join(row, " & "));
			out.println("\\\\");
		}
	}
}
